import { getHeaders } from '/@/utils/common/compUtils';
import { useGlobSetting } from '/@/hooks/setting';
import { getFileAccessHttpUrl } from '/@/utils/common/compUtils';

// 创建文件上传插件
export function registerFileUploadPlugin(tinymce) {
  // 文件上传URL - 使用完整的URL路径
  const { domainUrl } = useGlobSetting();
  // 确保domainUrl末尾没有斜杠，uploadPath开头有斜杠
  const uploadPath = '/sys/fileRecord/uploadRichTextFile';

  // 检查domainUrl是否包含上下文路径
  let uploadUrl = '';
  // 获取当前页面的上下文路径
  const currentPath = window.location.pathname;
  const contextPath = currentPath.substring(0, currentPath.indexOf('/', 1) || 0);
  console.log('当前上下文路径:', contextPath);

  if (domainUrl.includes('/jeecg-boot')) {
    // 如果domainUrl已经包含上下文路径
    uploadUrl = domainUrl + uploadPath;
  } else if (contextPath && contextPath !== '/') {
    // 如果当前页面有上下文路径
    uploadUrl = domainUrl + contextPath + uploadPath;
  } else {
    // 默认添加/jeecg-boot
    uploadUrl = domainUrl + '/jeecg-boot' + uploadPath;
  }
  
  console.log('文件上传插件URL:', uploadUrl);
  console.log('域名URL:', domainUrl);
  console.log('当前页面URL:', window.location.href);
  console.log('当前页面路径:', window.location.pathname);
  
  tinymce.PluginManager.add('fileupload', function(editor) {
    // 添加按钮
    editor.ui.registry.addButton('fileupload', {
      icon: 'upload',
      tooltip: '上传文件',
      onAction: function() {
        // 创建文件输入元素
        const input = document.createElement('input');
        input.setAttribute('type', 'file');
        input.setAttribute('accept', '.jpg,.jpeg,.png,.gif,.bmp,.webp,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.pdf,.txt,.mp3,.wav,.ogg,.flac,.aac,.mp4,.avi,.mov,.wmv,.flv,.mkv');
        
        // 文件选择后的处理
        input.onchange = function() {
          if (!input.files || input.files.length === 0) return;
          
          const file = input.files[0];
          
          // 检查文件大小
          const isLt10M = file.size / 1024 / 1024 < 10;
          if (!isLt10M) {
            editor.notificationManager.open({
              text: '文件大小不能超过10MB!',
              type: 'error',
              timeout: 3000
            });
            return;
          }
          
          // 检查文件类型
          const fileName = file.name;
          const extension = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase();
          const allowedTypes = [
            'jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp',
            'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'pdf', 'txt',
            'mp3', 'wav', 'ogg', 'flac', 'aac',
            'mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv'
          ];
          
          if (!allowedTypes.includes(extension)) {
            editor.notificationManager.open({
              text: '不支持的文件类型!',
              type: 'error',
              timeout: 3000
            });
            return;
          }
          
          // 显示上传中提示
          const loadingNotification = editor.notificationManager.open({
            text: '文件上传中...',
            type: 'info',
            closeButton: false
          });
          
          // 创建FormData
          const formData = new FormData();
          formData.append('file', file);
          formData.append('biz', 'richtext');
          formData.append('type', 'attachment');
          
          // 获取请求头
          const headers = getHeaders();
          
          // 发送请求
          const xhr = new XMLHttpRequest();
          xhr.open('POST', uploadUrl, true);
          
          // 添加请求头
          Object.keys(headers).forEach(key => {
            xhr.setRequestHeader(key, headers[key]);
          });
          
          xhr.onload = function() {
            if (xhr.status >= 200 && xhr.status < 300) {
              try {
                const result = JSON.parse(xhr.responseText);
                // 关闭上传中提示
                loadingNotification.close();
                
                if (result.success) {
                  const dbPath = result.result;
                  const extension = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase();
                  const url = getFileAccessHttpUrl(dbPath);
                  // 统一插入链接，无论文件类型，增加 class 和 data-file-type
                  if (["jpg","jpeg","png","gif","bmp","webp"].includes(extension)) {
                    editor.insertContent(`<img src="${url}" alt="${fileName}" style="max-width: 100%;" />`);
                  } else if (["mp4","avi","mov","wmv","flv","mkv","webm"].includes(extension)) {
                    editor.insertContent(`<video controls style="max-width: 100%;"><source src="${url}" type="video/${extension}">您的浏览器不支持视频播放</video>`);
                  } else if (["pdf"].includes(extension)) {
                    editor.insertContent(`<iframe src="${url}" style="width:100%;height:500px;" frameborder="0"></iframe>`);
                  } else {
                    editor.insertContent(`<a href="${url}" class="custom-file-link" data-file-type="${extension}" target="_blank" download="${fileName}">${fileName}</a>`);
                  }
                  // 显示成功提示
                  editor.notificationManager.open({
                    text: '文件上传成功',
                    type: 'success',
                    timeout: 2000
                  });
                } else {
                  // 显示错误提示
                  editor.notificationManager.open({
                    text: '文件上传失败: ' + (result.message || '未知错误'),
                    type: 'error',
                    timeout: 3000
                  });
                  console.error('上传失败响应:', result);
                }
              } catch (e) {
                // 关闭上传中提示
                loadingNotification.close();
                
                // 显示错误提示
                editor.notificationManager.open({
                  text: '文件上传失败: 服务器返回数据格式错误',
                  type: 'error',
                  timeout: 3000
                });
                console.error('解析服务器响应错误:', e);
                console.error('原始响应文本:', xhr.responseText);
                console.error('响应状态:', xhr.status, xhr.statusText);
              }
            } else {
              // 关闭上传中提示
              loadingNotification.close();
              
              // 显示错误提示
              editor.notificationManager.open({
                text: '文件上传失败: HTTP状态码 ' + xhr.status + ' ' + xhr.statusText,
                type: 'error',
                timeout: 3000
              });
              console.error('HTTP错误:', xhr.status, xhr.statusText);
              console.error('请求URL:', uploadUrl);
              console.error('请求头:', headers);
              try {
                console.error('响应内容:', xhr.responseText);
              } catch (e) {
                console.error('无法读取响应内容');
              }
            }
          };
          xhr.onerror = function(e) {
            // 关闭上传中提示
            loadingNotification.close();
            
            // 显示错误提示
            editor.notificationManager.open({
              text: '文件上传失败: 网络错误或服务器不可用',
              type: 'error',
              timeout: 3000
            });
            console.error('网络错误:', e);
          };
          xhr.send(formData);
        };
        
        // 触发文件选择
        input.click();
      }
    });
    
    // 添加菜单项
    editor.ui.registry.addMenuItem('fileupload', {
      text: '上传文件',
      icon: 'upload',
      onAction: function() {
        editor.execCommand('mceFileUpload');
      }
    });
    
    // 注册命令
    editor.addCommand('mceFileUpload', function() {
      editor.execCommand('mceFileUploadButton');
    });
    
    return {
      getMetadata: function() {
        return {
          name: 'File Upload Plugin',
          url: 'https://example.com/file-upload-plugin'
        };
      }
    };
  });
} 